package view;

import model.Rank;
import model.Suit;

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageInputStream;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

public class Card extends JPanel {
	/**
	 * 
	 */
	private static final long serialVersionUID = 6386593870807633140L;
	protected static final int WIDTH = 71; // Width of sub image
	protected static final int HEIGHT = 96; // Height of sub image
	private BufferedImage[][] theImages = null;
	private ImageIcon cardIcon = null;
	private BufferedImage cardCover = null;
	private boolean show;

	// change to enums
	public Card(Rank rank, Suit suit, int x, int y) {
		
		this.setPreferredSize(new Dimension(WIDTH, HEIGHT));
		this.intializeImages("Fancy.bmp");
		
		this.setSize(WIDTH, HEIGHT);
		
		this.setLocation(x, y);
		
		//cardCover = new BufferedImage("cover.png");
		try {
			
			cardCover=ImageIO.read(new File("img/" + "cover.png"));
			
		} catch (IOException e) {
			
			// TODO Auto-generated catch block
			e.printStackTrace();
			
		}
		cardIcon = new ImageIcon(theImages[rank.ordinal()][suit.ordinal()]);
		show = false;

	}

	protected void intializeImages(String file) {
		try {
			InputStream is = this.getClass().getClassLoader()
					.getResourceAsStream(file);
			ImageInputStream iis = ImageIO.createImageInputStream(is);
			BufferedImage theCompleteImage = ImageIO.read(iis);
			theImages = new BufferedImage[13][4];
			// int n = 0;
			for (int r = 0; r < 13; r++) {
				for (int s = 0; s < 4; s++) {
					theImages[r][s] = theCompleteImage.getSubimage(r * WIDTH, s
							* HEIGHT, WIDTH, HEIGHT);
				}
			}
		} catch (IOException ie) {
			JOptionPane.showMessageDialog(this, "Error",
					"Couldn't create image buffer.", JOptionPane.ERROR_MESSAGE);
		}
	}

	public void setShowCard(boolean show) {
		
		this.show = show;
		
	}
	
	public void stackCards(Point p){
		
		this.setLocation(p);
		
	}

	public void paintComponent(Graphics g) {
		
		super.paintComponent(g);
		if (show) {
			if (cardIcon != null) {
				cardIcon.paintIcon(this, g, 0, 0);
			}
		} else {
			if (cardCover != null) {
				//cardCover.paintIcon(this, g, 0, 0,WIDTH,HEIGHT);
				g.drawImage(cardCover,-3,-4,WIDTH+6,HEIGHT+6,this);
			}
		}
		
	}
	
	
	
}
